const crypto = require('crypto');
const proxy = require('http-proxy-middleware');

const ACCESS = '6D1655CCDC9C91826B5F0609C03E0D93';
const Secret = '3eef6425f9f5c6647516c765ddf46dbb215e1b0cc09cf7e291a4954a29f0720e';
const LINK = 'http://oss-cn-beijing.speedycloud.org'

module.exports = proxy({
    target: LINK,
    changeOrigin: true,
    logLevel: 'debug',
    pathRewrite: { '/upload': '' },
    onProxyReq(proxyReq, req) {
        console.log('__________________________');
        console.log(req.method, req.url, req.headers['filetype']);
        console.log('__________________________');

        const contentType = req.headers['filetype'];
        const date = new Date().toUTCString();
        const Authorization = `AWS ${ACCESS}:${ createSign(req.method, contentType, req.url, date) }`;
        
        proxyReq.setHeader('Date', date);
        proxyReq.setHeader('Authorization', Authorization);
        proxyReq.setHeader('Content-Type', contentType);
    }
});

function createSign (httpMethod, contentType, url, date) {
    const signStr = `${httpMethod}\n\n${contentType}\n${date}\n${url}`;
    const hash = crypto.createHmac('sha1', Secret);
    hash.update(signStr);

    return hash.digest().toString('base64');
}